<template>
  <view style="background:#f3f4f6">
    <!-- 顶部固定区域 -->
    <view class="headers"></view>
    <view class="fixed-top">
      <view style="background:rgba(0,0,0,0);margin:15rpx;border-radius:15rpx;margin-bottom: 20rpx; display: flex">
        <view style="margin:20rpx 0 0 20rpx;width: 10%">
          <u-icon
              name="arrow-left"
              size="24"
              color="#333"
              @click="goBack"
              style="cursor: pointer;"
          ></u-icon>
        </view>
        <!--           <view style="display: flex;justify-content: center;align-items: center;width: 70%">-->
        <!--             <u-tabs :activeStyle="{-->
        <!--                   color: '#000',-->
        <!--                   fontWeight: '800'-->
        <!--                 }" lineWidth="70" lineColor="#25772f" :list="tab_list" @click="tab_click"-->
        <!--                     :current="seach_type"></u-tabs>-->
        <!--           </view>-->
      </view>
      <view v-show="seach_type ==0">
        <view style="margin-bottom: 13rpx;padding: 15rpx 30rpx;">
          <u-search :show-action="true" actionText="搜索" :animation="false" @custom="get_information(true)"
                    @search="get_information(true)" v-model="information_form.keyword"></u-search>
        </view>
        <view style="margin-top: -15rpx;width: 100%; background:rgba(0,0,0,0)">
          <sl-filter :ref="'slFilter'" :isTransNav="true" :navHeight="0" :menuList="menuList"
                     @result="filter_confirm" @letterClick="onLetterClick"></sl-filter>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-wrapper">
      <view class="content">
        <view
            style="margin:8px;border-radius:8px;min-height:300px;display:flex;align-items:center;justify-content:center;"
            v-if="page_loding == 'nomore' && $u.test.isEmpty(information_list)">
          <u-empty mode="news" icon="/static/empty_list.png" text="暂时没有内容"
                   style="margin-bottom: 25rpx;"></u-empty>
        </view>
        <informationList v-else  ref="information_list" :information_list="information_list" :user_info="userInfo"
                         @click_item="to_information" @like-update="handleLikeUpdate"></informationList>
        <u-loadmore :status="page_loding" loading-text="加载中..." loadingIcon="spinner"
                    v-if="!(page_loding == 'nomore' && $u.test.isEmpty(information_list))"/>
      </view>


      <view v-show="seach_type ==1" class="map-container">
        <!-- 地图内容保持不变 -->
      </view>
    </view>
  </view>
</template>

<script>
import informationList from "@/components/information-list/information-list3.vue"
// import informationList2 from "@/components/information-list/information-list2.vue"
import slFilter from '@/components/sl-filter/sl-filter.vue'
import {url} from "../../uni_modules/uv-ui-tools/libs/function/test";

export default {
  components: {
    informationList,
    // informationList2,
    slFilter
  },
  data() {
    return {
      error_num: 2,
      page_loding: "loading",
      title: '信息列表',
      information_form: {
        page: 0,
        keyword: '',
        distance: 5,
        size: 6,
        treeSpecies: '',
        bestPeriod: '',
        category: '',
        address: '',
      },
      information_list: [],
      userInfo: [],
      tab_list: [{
        name: '常规模式',
        value: 1
      },
        /* {
             name: '地图',
             value: 2
           } */
      ],
      menuList: [
        {
          'title': '树种',
          'detailTitle': '',
          'isMutiple': false,
          'key': 'treeSpecies',
          'hasLetterFilter': true, // 支持字母筛选
          'showLetterNav': true, // 在展开内容中显示字母导航
          detailList: []
        },
        {
          'title': '佳期',
          'detailTitle': '',
          'isMutiple': false,
          'key': 'bestPeriod',
          detailList: []

        },
        {
          'title': '类别',
          'detailTitle': '',
          'key': 'category',
          'isSort': true,
          'isMutiple': false,
          // 'defaultSelectedIndex': 1,
          detailList: []

        },
        {
          'title': '地区',
          'detailTitle': '',
          'isArea': true,
          'isSort': false,
          'key': 'address',
          'isMutiple': false,
          'defaultSelectedIndex': 0,
          detailList: []
        }
      ],
      seach_type: 0,
      dictValue: 5,
      
      // 字母导航相关
      showLetterNav: false, // 是否显示字母导航
      letterList: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'], // 字母列表
      currentLetter: '', // 当前选中的字母
      
      //     地图
      // 地图中心点坐标
      longitude: '',
      latitude: '',
      province: '',
      // 缩放级别
      scale: 8,
      // 标记点数组
      markers: [],
      // 路线
      polyline: [{
        points: [{
          longitude: 113.3245211,
          latitude: 23.10229
        }, {
          longitude: 113.324520,
          latitude: 23.099994
        }],
        color: "#FF0000DD",
        width: 2,
        dottedLine: true
      }],
      // 控件
      controls: [{
        id: 1,
        iconPath: '',
        position: {
          left: 20,
          top: 200 - 50,
          width: 40,
          height: 40
        },
        clickable: true
      }]
    }
  },
  // onShareAppMessage(res) {
  // 	if (res.from === 'button') {
  // 	  console.log(res.target)
  // 	}
  // 	return {
  // 	  title: '【' + this.title + '】❤这里是渝快同城-重庆自己人的圈子~',
  // 	  path: '/pages/index/index',
  // 	  imageUrl: this.$baseUrl + "/share_logos.png"
  // 	}
  // },
  // onShareTimeline(res) {
  // 	if (res.from === 'button') {
  // 	  console.log(res.target)
  // 	}
  // 	return {
  // 	  title: '【' + this.title + '】❤这里是渝快同城-重庆自己人的圈子~',
  // 	  imageUrl: this.$baseUrl + "/share_logos.png"
  // 	}
  // },
  onLoad(e) {
    // console.log('key', e.category_id);
    // this.information_form.category_id = e.category_id
    // switch(e.category_id){
    // 	case '23':
    // 	case '14':
    // 		let appendData = [
    // 			{
    // 				'title': '价格从高到低',
    // 				'value': 'price_desc',
    // 			},
    // 			{
    // 				'title': '价格从低到高',
    // 				'value': 'price_asc',
    // 			},
    // 			{
    // 				'title': '不看面议价',
    // 				'value': 'not_look_price',
    // 			},
    // 		]
    // 		this.menuList[3]['detailList'] = this.menuList[3]['detailList'].concat(appendData)
    // 	break;
    // 	default:
    // }
    this.longitude = uni.getStorageSync('longitude')
    this.latitude = uni.getStorageSync('latitude')
    this.get_information()
    this.get_tree_map_num()
    this.get_province()
  },
  onPullDownRefresh() {
    this.init()
  },
  async onReachBottom() {
    await this.get_information()
  },
  methods: {
    /**
     * 下拉刷新初始化方法
     */
    init() {
      this.information_form.page = 0
      this.information_list = []
      if (this.$refs.information_list) {
        this.$refs.information_list.foreFlowView() // 清空瀑布流
      }
      this.get_information(true).finally(() => {
        uni.stopPullDownRefresh() // 停止下拉刷新
      })
    },
    /**
     * 选择小区
     */
    async select_community() {
      let locat = await this.$get_location()
      uni.chooseLocation({
        latitude: locat.latitude,
        longitude: locat.longitude,
        success: (res) => {
          // this.add_form.name = res.name
          console.log(1111, res)
          this.longitude = res.longitude
          this.latitude = res.latitude
          this.information_form.keyword = res.address
          this.get_information(true)
        }
      });

    },
    /**
     * 获取省份
     */
    // /system/provinceCity/regions/province?lon=116.231&lat=40.221  --GET
    async get_province() {
      return new Promise((suc, err) => {
        this.$http.to_http(`system/provinceCity/regions/province`, {
          lat: this.latitude,
          lon: this.longitude,
        }, 'GET', false).then(res => {
          res = res.data
          if (res.code != 200) {
            return
          }
          this.province = res.data
          this.get_dictType()
          uni.setStorageSync('province', res.data)
          console.log(9999, res.data)
        })
      })
    },
    // 放大地图
    zoomIn() {
      if (this.scale < 20) {
        this.scale += 1;
      }
    },

    // 缩小地图
    zoomOut() {
      if (this.scale > 4) {
        this.scale -= 1;
      }
    },
    addMarker() {
      // 随机生成标记点
      const marker = {
        id: this.markers.length + 1,
        longitude: this.longitude + (Math.random() - 0.5) * 0.02,
        latitude: this.latitude + (Math.random() - 0.5) * 0.02,
        title: `标记点${this.markers.length + 1}`,
        iconPath: '/static/marker.png',
        width: 30,
        height: 30,
        callout: {
          content: `这是第${this.markers.length + 1}个标记点`,
          color: '#fff',
          bgColor: '#25772f',
          padding: 10,
          borderRadius: 5,
          display: 'ALWAYS'
        }
      }
      console.log(22222, marker)
      this.markers.push(marker);
      uni.showToast({
        title: '添加标记成功',
        icon: 'success'
      });
    },

    // 清除所有标记点
    clearMarkers() {
      this.markers = [];
      uni.showToast({
        title: '已清除所有标记',
        icon: 'none'
      });
    },

    // 标记点点击事件
    markerTap(e) {
      const marker = this.markers.find(m => m.id === e.markerId);
      uni.navigateTo({
        url: "/packageB/information/information?information_id=" + marker.ids + '&lat=' + marker.latitude + '&lon=' + marker.longitude
      })
      // const marker = this.markers.find(m => m.id === e.markerId);
      // if (marker) {
      //     uni.showModal({
      //         title: marker.title,
      //         content: marker.callout.content,
      //         showCancel: false
      //     });
      // }
    },

    // 控件点击事件
    controlTap(e) {
      console.log('点击控件', e);
      // if (e.controlId === 1) {
      //     this.moveToLocation();
      // }
    },

    // 移动到定位点
    moveToLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.longitude = res.longitude;
          this.latitude = res.latitude;
          uni.showToast({
            title: '已定位到当前位置',
            icon: 'none'
          });
        },
        fail: (err) => {
          console.error('获取位置失败', err);
          uni.showToast({
            title: '获取位置失败，请检查权限',
            icon: 'none'
          });
        }
      });
    },

    // 地图区域变化事件
    regionchange(e) {
      console.log('地图区域变化', e.type);
    },
    // 地图结束
    handleLikeUpdate({index, newCount, liked}) {
      console.log(index, newCount, liked)
      // 确保响应式更新
      this.$set(this.information_list, index, {
        ...this.information_list[index],
        liked,
        tree: {
          ...this.information_list[index].tree,
          likeCount: newCount,
        }
      });
    },
    goBack() {
      // 尝试返回上一页
      uni.navigateBack({
        fail: (err) => {
          // 如果无法返回上一页，则跳转到首页
          console.log('无法返回上一页，跳转到首页', err);
          uni.switchTab({
            url: '/pages/index/index'
          });
        }
      });
    },
    // 类型
    get_dictType() {
      return new Promise((suc, err) => {
        this.$http.to_http(`system/dict/data/typeApi/dictType`, {}, 'GET', false).then(res => {
          res = res.data
          if (res.code != 200) {
            return uni.showToast({
              title: "获取类型失败",
              icon: "none"
            })
          }
          let finindex = res.data['tree_province'].findIndex((item) => item.title == this.province)
          
          // 直接使用原始的树种数据，不添加字母导航项
          this.menuList[0].detailList = res.data['tree_varieties'] || []
          
          this.menuList[1].detailList = res.data['tree_species'] || []
          this.menuList[2].detailList = res.data['tree_category'] || []
          // this.menuList[3].defaultSelectedIndex = finindex
          if (finindex) {
            uni.setStorageSync('provinceIndex', finindex)
          }
          this.menuList[3].detailList = res.data['tree_province'] || []
          
          // 检查是否需要显示字母导航（只在树种数据存在时显示）
          this.showLetterNav = this.menuList[0].detailList && this.menuList[0].detailList.length > 0

        })
      })
    },
    
    // 字母点击事件
    onLetterClick(letter) {
      this.currentLetter = letter
      
      // 调用接口获取对应字母的树种数据
      this.getTreeSpeciesByLetter(letter)
    },
    
    // 根据字母获取树种数据
    getTreeSpeciesByLetter(letter) {
      const params = {
        initial: letter,
        // 可以添加其他参数
      }
      
      this.$http.to_http('system/dict/data/filterByInitial', params, 'GET', '加载中').then(res => {
        res = res.data
        if (res.code !== 200) {
          uni.showToast({
            title: res.msg || '获取数据失败',
            icon: 'none'
          })
          return
        }
        
        // 直接更新树种筛选数据
        const newTreeSpecies = res.data.tree_varieties || []
        console.log('树种筛选数据:', newTreeSpecies)
        this.menuList[0].detailList = newTreeSpecies
        
        // 强制更新sl-filter组件
        this.$nextTick(() => {
          if (this.$refs.slFilter && this.$refs.slFilter.resetMenuList) {
            this.$refs.slFilter.resetMenuList(this.menuList)
          }
          // 强制组件重新渲染
          this.$forceUpdate()
        })
        
        console.log(`字母 ${letter} 对应的树种数据:`, res.data)
        
        // 可以选择是否自动触发信息列表的更新
        // this.get_information(true)
      }).catch(err => {
        console.error('获取树种数据失败:', err)
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        })
      })
    },
    clickBtn() {
      uni.showModal({
        title: "发布提示",
        content: "本功能需要登录后使用，请在首页登录后点击下方菜单“我要发布”进行选择板块分类即可发布",
        showCancel: false,
        confirmText: "知道啦",
        success(res) {
          if (res.confirm) {
            uni.switchTab({
              url: "/pages/index/index"
            })
          }
        }
      })
    },

    to_information(item) {
      uni.navigateTo({
        url: "/packageB/information/information?information_id=" + item.id + '&lat=' + item.latitude + '&lon=' + item.longitude
      })
    },
    tab_click(item) {
      this.seach_type = item.index
      this.information_form = {
        page: 0,
        keyword: '',
        distance: 5,
        size: 5,
        treeSpecies: '',
        bestPeriod: '',
        category: '',
        address: '',
      }
      if (item.index == 1) {
        this.information_form.size = this.dictValue;
      } else {
        this.information_form.size = 5
        // this.$refs.information_list.foreFlowView(); // 清空瀑布流
      }
      this.page_loding = 'loading'
      this.information_list = [];

      this.get_information()
    },
    /**
     * 筛选确认回调
     * @param {Object} e
     */
    filter_confirm(e) {
      // 如果是字母点击，只关闭弹窗，不处理筛选逻辑
      if (e.isLetterClick) {
        // 不关闭弹框，直接返回
        return;
      }
      
      // 按原有逻辑处理筛选结果
      this.information_form.bestPeriod = e.bestPeriod
      this.information_form.category = e.category
      if (e.titles) {
        this.information_form.address = e.titles == '全部' ? '' : e.titles
      } else {
        let address = this.menuList[3].detailList.find((item) => item.value == e.address)
        console.log("=address==>", address)
        this.information_form.address = address?.title ? address.title == '全部' ? '' : address.title : ''
      }

      let treeSpecies = this.menuList[0].detailList.find((item) => item.value == e.treeSpecies)

      this.information_form.treeSpecies = treeSpecies?.title ? treeSpecies.title == '全部' ? '' : treeSpecies.title : ''
      this.get_information(true) // 筛选时强制刷新
    },
    /**
     * 获取信息列表
     */
    get_information(is_force = false) {
      if (is_force) {
        this.information_list = []
        this.information_form.page = 0
        this.$refs.information_list.foreFlowView(); // 清空瀑布流
      }
      this.page_loding = 'loading'
      return new Promise((suc, err) => {
        let information_form = uni.$u.deepClone(this.information_form) // 对象深度克隆
        if (this.seach_type == 1) {
          information_form.lon = this.longitude
          information_form.lat = this.latitude
        } else {
          information_form.lon = uni.getStorageSync('longitude')
          information_form.lat = uni.getStorageSync('latitude')
        }
        console.log(8888, information_form)
        this.$http.to_http('search/trees/keyword', information_form, 'GET', is_force ? '加载中' : false).then(res => {
          res = res.data
          if (res.code != 200) {
            return uni.showToast({
              title: "系统维护中",
              icon: "none"
            })
          }
          // if(res.data.total>0){
          // this.title = res.data.rows[0].category.name
          // }
          if (res.data.content.length > 0) {
            this.information_form.page++;
          }
          if (res.data.totalPages > this.information_form.page) {
            this.page_loding = 'loadmore'
          } else {
            setTimeout(() => {
              this.page_loding = 'nomore'
            }, 1000)
          }
          if (res.data.content.length > 0) {
            if (this.seach_type == 1) {
              this.longitude = res.data.content[0].tree.longitude
              this.latitude = res.data.content[0].tree.latitude
              this.scale = 15
            }
            res.data.content.forEach(el => {
              if (this.seach_type == 1) {
                const marker = {
                  id: this.markers.length + 1,
                  longitude: el.tree.longitude,
                  latitude: el.tree.latitude,
                  title: el.tree.name,
                  iconPath: el.tree.imageUrl,
                  ids: el.tree.id,
                  width: 40,
                  height: 40,
                  callout: {
                    content: el.tree.name,
                    color: '#3d3d3d',
                    padding: 5,
                    borderWidth: 2,
                    borderColor: '#fff',
                    borderRadius: 10,
                    fontSize: 16,
                    display: 'ALWAYS'
                  }
                }

                this.markers.push(marker);
              }
              this.information_list.push(el)
            })
          } else {
            // uni.showToast({
            //   title: "暂无数据",
            //   icon: "none"
            // })
          }
          // 根据是否强制刷新来决定调用init还是appendData
          if (is_force) {
            this.$refs.information_list.init(this.information_list) // 初始化
          } else {
            this.$refs.information_list.appendData(res.data.content) // 追加数据
          }

          suc(true);
        }).catch(async err => {
          if (err.statusCode = 401 && this.error_num > 0) {
            this.error_num--
            // await this.$wechatLogin()
            // await this.get_information()
          }
          suc(true);
        })
      })
    },
    get_tree_map_num(is_force = false) {
      return new Promise((suc, err) => {
        let information_form = {}// 对象深度克隆
        information_form.lon = uni.getStorageSync('longitude')
        information_form.lat = uni.getStorageSync('latitude')
        console.log(8888, location)
        this.$http.to_http('system/dict/data/typeApi/tree_map_num', information_form, 'GET', is_force ? '加载中' : false).then(res => {
          res = res.data
          if (res.code != 200) {
            return uni.showToast({
              title: "请求失败",
              icon: "none"
            })
          }
          this.dictValue = res.data[0].dictValue
          suc(true);
        }).catch(async err => {

          suc(true);
        })
      })
    },
  }
}
</script>

<style scoped lang="scss">
.content {
  //background:#f3f4f6;
  padding-bottom: 10px;
}

/* 新增的固定顶部样式 */
.fixed-top {
  position: fixed;
  padding-top: 70rpx;
  left: 0;
  right: 0;
  z-index: 100;
  height: auto !important;
  background-image: url('http://xaiohua.oss-cn-beijing.aliyuncs.com/medias/trees/treeId/images/56ea2705-adb5-4a12-848c-8fbe12e9a179.png?Expires=4907190184&OSSAccessKeyId=LTAI5t93GNuNHEtLjPm4NWTG&Signature=mJQMCS3RjUe%2FrD8Q%2FiLLXIHmk3A%3D');
  background-size: cover;
  //background: #f3f4f6;
}

/* 内容区域需要添加padding-top避免被遮挡 */
.content-wrapper {
  position: absolute;
  top: 350rpx;
  z-index: 99;
  width: 100%;
}


.headers {
  background-image: url('http://xaiohua.oss-cn-beijing.aliyuncs.com/medias/trees/treeId/images/56ea2705-adb5-4a12-848c-8fbe12e9a179.png?Expires=4907190184&OSSAccessKeyId=LTAI5t93GNuNHEtLjPm4NWTG&Signature=mJQMCS3RjUe%2FrD8Q%2FiLLXIHmk3A%3D');
  //height: 500rpx;
  width: 100%;
  background-size: cover;
  padding-top: 100rpx;
  position: fixed;
  z-index: 1;
  top: 0;
}

.control-group {
  display: flex;
  flex-direction: column;
  position: fixed;
  left: 10rpx;
  top: 45%;
}

.control-btn {
  width: 80rpx;
  height: 90rpx;
  background-color: #25772f;
  //border-radius: 10rpx;
  //box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 60rpx;
  color: #fff;
  font-weight: bold;
  cursor: pointer;
}
</style>

